import threading
import time
import random


class TheThread(threading.Thread):

    def __init__(self, tid, count, mutex):
        threading.Thread.__init__(self)
        self.tid = tid
        self.count = count
        self.mutex = mutex

    def run(self):
        f = open('/dev/urandom', 'rb')
        for i in range(self.count):
            size = random.randint(1, 1024)
            with self.mutex:
                data = f.read(size)
                print('[%s]: read %s bytes' % (self.tid, size))
            time.sleep(0.3)


if __name__ == '__main__':

    mutex = threading.Lock()
    threads = []

    for i in range(7):
        thread = TheThread(i, 3, mutex)
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

    print('Main thread exiting.')
